import _ from 'lodash';

export default {
  namespace: 'user',
  state: {
    session_key: 'user_session',
    login: false,
    administrator: null,
    current_org: null,
    orgs: null,
  },
  subscriptions: {
    setup({ dispatch }) {
      dispatch({
        type: 'RefactoringSission',
        payload: {},
      });
    }
  },
  effects: {
    *initialization({ payload: { administrator, orgs } }, { put }) {
      yield put({
        type: 'change',
        payload: {
          administrator: {
            id: administrator.id,
            username: administrator.username,
            realname: administrator.realname,
            avatar: administrator.avatar,
            member_code: administrator.member_code,
          },
          orgs: _.map(orgs, row => ({
            org_code: row.org_code,
            org_zb_code: row.org_zb_code,
            org_name: row.org.name,
          })),
        }
      });
    },
    *change({ payload }, { put }) {
      yield put({
        type: 'changeSission',
        payload,
      });
      yield put({
        type: 'changeData',
        payload
      });
      yield put({
        type: 'changeCurrentOrg',
        payload: 0,
      });
    },
    *remove({ payload }, { put }) {
      yield put({ type: 'removeSission' });
      yield put({ type: 'removeData' });
    },
    *changeSission({ payload }, { call, select }) {
      const sessionKey = yield select(state => state.user.session_key);
      const sessionValue = JSON.stringify(payload);
      yield sessionStorage.setItem(sessionKey, sessionValue);
    },
    *removeSission({ payload }, { call, select }) {
      const sessionKey = yield select(state => state.user.session_key);
      yield sessionStorage.removeItem(sessionKey);
    },
    *RefactoringSission( aaa, { call, put, select }) {
      const sessionKey = yield select(state => state.user.session_key);
      const sessionValue = yield sessionStorage.getItem(sessionKey);
      if ( sessionValue ) {
        yield put({
          type: 'changeData',
          payload: JSON.parse(sessionValue),
        });
        yield put({
          type: 'changeCurrentOrg',
          payload: 0,
        });
      }
    }
  },
  reducers: {
    changeCurrentOrg( state, action) {
      return {
        ...state,
        current_org: state.orgs[action.payload],
      };
    },
    changeData( state, action) {
      const login = Boolean(action.payload);
      return {
        ...state,
        ...action.payload,
        login,
      };
    },
    removeData( state) {
      return {
        ...state,
        data: null,
        login: false,
      };
    }
  }
};
